package mysql

import (
	"common/models"
	setting "common/viper"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

const (
	LikeType = "%"
)

// 建立数据库连接
// 全局的数据库对象DB
type Mysql struct {
	Db *gorm.DB
}

func Init(cfg *setting.MySQLConfig) (err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		cfg.User,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.DbName,
	)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		zap.L().Error("connect DB failed", zap.Error(err))
		return
	}
	//创建表
	if cfg.CreateTable {
		db.AutoMigrate(&models.UserInfo{}, &models.GroupInfo{}, &models.MsgInfo{}, &models.ImageInfo{}, &models.Message{})
	}
	return
}
func NewMysql() Mysql {
	return Mysql{Db: db}
}
